<!-- 
	* 摘要：箱码生成
	* 软件名称：雪克码数据管理系统1.0
	* 文件名: boxcode.vue
	* 版本：1.0
 -->
<template>
	<div class="sn-common-container ">
		<div class="prcoss-container">
			<header>
				<div class="sn-flex sn-row-center hidden-sm-and-down">
					<el-select v-model="itemStatus" value-key="" placeholder="是否成功" @change="currentChange(1)" style="width: 120px;margin-right: 10px;" clearable filterable >
						<el-option :label="'全部'" :value="'all'"></el-option>
						<el-option :label="'已成功'" :value="true"></el-option>
						<el-option :label="'未成功'" :value="false"></el-option>
					</el-select>
					<el-select v-model="searchShop"  placeholder="选择店铺"  filterable style="width: 160px;margin-right: 10px;"  @change="currentChange(1)">
						<el-option v-for="item in shopList"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
					<el-input v-model="searchValue" placeholder="输入批次名称进行筛选" style="width: 160px;margin-right: 10px;" clearable
						@keyup.enter.native="currentChange(1)" />
						<el-input v-model="searchBoxSize" placeholder="输入箱规进行筛选" style="width: 160px;margin-right: 10px;" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-date-picker v-model="BeginTime" type="datetime" style="margin-right: 10px; width: 150px;" placeholder="开始时间"  @change="currentChange(1)"></el-date-picker>
					<el-date-picker v-model="EndTime" default-time="23:59:59" type="datetime" placeholder="结束时间" style="width: 150px;"  @change="currentChange(1)"></el-date-picker>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
						@click="currentChange(1)">
						搜索
					</el-button>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
						@click="addTransferOpen()">
						新增批次
					</el-button>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
						@click="importCodeDialog = true;">
						导入
					</el-button>
					<el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-download"
						@click="exportCodeDialog = true;">
						导出空码
					</el-button>
				</div>
				<div class="hidden-sm-and-up">
					<el-input v-model="searchValue" placeholder="输入商品名称进行筛选" style="width: 200px" clearable
						@keyup.enter.native="currentChange(1)" />
					<el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
						@click="currentChange(1)">
					</el-button>
					<el-button class="sn-btn" style="margin-left: 4px" type="primary" icon="el-icon-plus"
						@click="addTransferOpen()">
						添加
					</el-button>
				</div>
			</header>
			<section> 
				<global-table :loading="tableLoading" style="margin-top: 20px;" :pageIndex="currentPage" :pageSize="pageSize" :headerData="initData"
					:data="tabelData" :isFullScreen="false" :operateW="250">
					<template #quantity="scope">
						<span>{{ scope.row.success ? scope.row.actualQuantity : scope.row.actualQuantity + '/' + scope.row.generateQuantity }}</span>
					</template>
					<template #createdTime="scope">
						{{$parseTime(scope.row.createdTime,'{y}-{m}-{d} {h}:{i}')}}
					</template>
					<template #completionTime="scope">
						{{scope.row.completionTime?$parseTime(scope.row.completionTime,'{y}-{m}-{d} {h}:{i}'):'--'}}
					</template>
					<template #operate="scope">
						<!-- <div v-if="itemStatus === true">
							<el-button type="primary" size="mini" @click="resetDeleteFn(scope.row.id)">恢复删除</el-button>
							<el-button type="primary" size="mini" class="sn-btn" @click="deleteItemFn(scope.row.id,true)">彻底删除</el-button>
						</div> -->
						<el-button  v-if="scope.row.completionTime" type="primary" size="mini" @click="lookCodeBtnClick(scope.row.id,scope.row.name)">查看</el-button>
						<div  v-if="!scope.row.completionTime">
							<el-button type="primary" size="mini" @click="lookProgress(scope.row.id,scope.row.name)">查看生成进度</el-button>
							<el-button type="primary" size="mini" class="sn-btn" @click="cancelGenerate(scope.row.id)">取消生成</el-button>
						</div>
						<el-button type="primary" size="mini" class="sn-btn"  v-else @click="deleteItemFn(scope.row.id,true)">删除</el-button>
					</template>
				</global-table>
			</section>
			<footer style="margin-top: 20px;">
				<el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
					layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-page
					style="text-align: center;" :total="totalNum" background>
					>
				</el-pagination>
			</footer>
		</div>
		<!-- 编辑或新增弹窗 -->
		<el-dialog :visible.sync="addBottleDialog" class="sn-default-dialog" width="360px" @close="roleDialogClose()">
			<div class="sn-title" slot="title">新增批次</div>
			<div v-loading="addBottleLoading">
				<p class="sn-must-label">批次名称：</p>
				<el-input type="text" maxlength="30" show-word-limit v-model="bottleConfig.name" placeholder="请输入批次名称" style=""></el-input>
				<p class="sn-must-label">箱规：</p>
				<el-input-number style="width: 200px;" v-model="bottleConfig.boxSize" controls-position="right"  :min="1" :max="50" :step="1"></el-input-number>
				<p class="sn-must-label">总箱数：</p>
				<el-input-number style="width: 200px;" v-model="bottleConfig.generateQuantity" controls-position="right"  :min="1" :max="99999" :step="1"></el-input-number>
				<p style="text-align: center;">
					<el-button type="primary" size="medium" class="sn-btn" @click="createBottleCodeFn()">保存</el-button>
					<el-button size="medium" @click="addBottleDialog = false">取消</el-button>
				</p>
			</div>
		</el-dialog>
		<el-dialog
		:visible.sync="progressDialog"
		class="sn-default-dialog"
		@close="progressDialogClose()"
		width="375px"
		>
		<div class="sn-title" slot="title">生成箱码进度</div>
		<div class="sn-flex sn-row-center">
			<el-progress type="dashboard" :percentage="percentage" :color="colors"></el-progress>
		</div>
		<p style="text-align:center;">
				{{progressText}}
			</p>
		</el-dialog>
		<el-dialog
		:visible.sync="lookBoxCodeDialog"
		class="sn-default-dialog"
		>
		<div class="sn-title" slot="title">{{boxCodeName}}</div>
		<div>
			<box-code :codeId="boxCodeId" :codeName="boxCodeName" @refreshData="getDataListFn" v-if="lookBoxCodeDialog"></box-code>
		</div>
		</el-dialog>
		<el-dialog
		:visible.sync="importCodeDialog"
		class="sn-default-dialog"
		width="500px"
		>
		<div class="sn-title" slot="title">导入箱码</div>
		<div v-loading="importLoading">
			<div class="sn-flex">
				<p style="margin-right: 20px;">上传Excel:</p>
				<upload-file v-if="importCodeDialog" @imageUpload="excelUploadFn" :isToLocal="true" @imageRemove="excelRemoveFn"></upload-file>
			</div>
			<div class="sn-flex">
				<p>批次名称:</p>
				<el-input v-model="importCodeInfo.name" placeholder="批次名称" style="width: 200px;margin-left: 20px;" size="normal" clearable ></el-input>
			</div>
			<div class="sn-flex">
				<p>箱码列名:</p>
				<el-input v-model="importCodeInfo.boxHeaderName" placeholder="输入箱码对应列名" style="width: 200px;margin-left: 20px;" size="normal" clearable ></el-input>
			</div>
			<p style="text-align:center;margin-bottom: 0;">
				<el-button type="primary" size="medium" class="sn-btn" @click="importCodeFn()">保存</el-button>
				<el-button size="medium" @click="importCodeDialog = false">取消</el-button>
			</p>
		</div>
		</el-dialog>
		<el-dialog
		:visible.sync="exportCodeDialog"
		class="sn-default-dialog"
		width="500px"
		>
		<div class="sn-title" slot="title">导出空码</div>
		<div v-loading="exportLoading">
			<div class="sn-flex" style="margin-bottom: 20px;">
				<p>类型:</p>
				<el-select v-model="exportCodeInfo.codeType" placeholder="请选择码类型" style="width: 200px;margin-left: 20px;" size="normal"  >
					<el-option :label="'瓶码'" :value="0"></el-option>
					<el-option :label="'箱码'" :value="1"></el-option>
					<el-option :label="'托码'" :value="2"></el-option>
				</el-select>
			</div>
			<div class="sn-flex">
				<p style="margin-right: 20px;">数量:</p>
				<el-input-number v-model="exportCodeInfo.count" size="normal" 
					:min="1" :max="9999999" :step="1" :controls="true" controls-position="both">
				</el-input-number>
			</div>
			<p style="text-align:center;margin-bottom: 0;">
				<el-button type="primary" size="medium" class="sn-btn" @click="exportCodeFn()">保存</el-button>
				<el-button size="medium" @click="exportCodeDialog = false">取消</el-button>
			</p>
		</div>
		</el-dialog>
	</div>
</template>
<script>
import GlobalTable from '@/components/GlobalTable';
import {GetTaskCompletionRatios,GetBoxCodeBatchesPage,DeleteBoxCodeBatch,StartGenerateCombinationCodesTask,CancelTask,StartImportBoxCodesTask,GenerateCodes} from '@/api/bottleCode';
import {  GetEnterprisesByPage} from '@/api/enterprise';
import { guid } from '@/utils'
import BoxCode from '@/views/fillBox/boxcode/BoxCode';
import UploadFile from '@/components/UploadFile';
export default {
	components: { GlobalTable,BoxCode,UploadFile },
	data() {
		return {
			tableLoading:false,
			importCodeDialog:false,
			exportCodeDialog:false,
			tabelData: [],
			initData: [
				{
					label: '批次名称',
					value: 'name',
					id: guid(),
					width: 200
				},
				{
					label: '箱规',
					value: 'boxSize',
					id: guid(),
				},
				{
					label: '生成数量',
					value: 'quantity',
					id: guid(),
					isCustom:true
				},
				{
					label: '创建时间',
					value: 'createdTime',
					id: guid(),
					isCustom:true
				},
				{
					label: '完成时间',
					value: 'completionTime',
					id: guid(),
					isCustom:true
				},
			],
			currentPage: 1,
			pageSize: 10,
			totalNum: 0,
			searchValue: '',
			searchBoxSize:'',
			itemStatus:'all',
			addBottleDialog: false,
			addBottleLoading: false,
			bottleConfig:{
				boxSize:1,
				generateQuantity:1,
				name:''
			},
			colors: [
				{color: '#f56c6c', percentage: 20},
				{color: '#e6a23c', percentage: 40},
				{color: '#5cb87a', percentage: 60},
				{color: '#1989fa', percentage: 80},
				{color: '#6f7ad3', percentage: 100}
			],
			percentage:0,
			progressDialog:false,
			timer:null,
			progressText:'',
			BeginTime:'',
			EndTime:'',
			boxCodeName:'',
			lookBoxCodeDialog:false,
			boxCodeId:'',
			shopList:[],
			searchShop:'',
			importCodeInfo:{
				boxHeaderName:'箱码',
				resourceId:'',
				name:'',
			},
			importLoading:false,
			exportCodeInfo:{
				count:1,
				codeType:0,
			},
			exportLoading:false,
		}
	},
	computed: {
		tableHeight() {
			return this.$store.state.common.mainHeight - 230;
		}
	},
	watch: {
		searchValue(val) {
			this.currentPage = 1;
			this.getDataListFn();
		}
	},
	created() {
		this.getDataListFn();
		this.getShopListFn();
	},
	methods: {
		async exportCodeFn(){
			try {
				this.exportLoading = true;
				const res = await GenerateCodes(this.exportCodeInfo);
				this.exportLoading = false;
				if (res.code!==500) {
					this.$message.success("空码导出成功，正在下载...");
					let blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
					if ("download" in document.createElement("a")) {
						// 非IE下载
						const elink = document.createElement("a");
						// let fileName= window.decodeURI(res.headers['content-disposition'].split('=')[1], "UTF-8")
						let fileName = `空码-${this.codeName}`;
						elink.target = "hrefTemplate";
						elink.download = fileName;
						elink.href = URL.createObjectURL(blob);
						elink.click();
						URL.revokeObjectURL(elink.href); // 释放URL 对象
					} else {
						// IE10+下载
						navigator.msSaveBlob(blob, fileName);
					}
				} else {
					this.$message.error('导出空码失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.exportLoading = false;
				this.$message.error('导出空码失败，错误信息：' + error);
			}
		},
		// 导入箱码
		async importCodeFn(){
			this.importLoading = true;
			if(this.importCodeInfo.resourceId===''){
				this.$message.error('请上传Excel文件');
				this.importLoading = false;
				return;
			}
			if(this.importCodeInfo.boxHeaderName===''){
				this.$message.error('请输入箱码列名');
				this.importLoading = false;
				return;
			}
			this.importCodeInfo.enterpriseId = this.searchShop;
			let res = await StartImportBoxCodesTask(this.importCodeInfo);
			this.importLoading = false;
			if(res.code===200){
				this.importCodeDialog = false;
				this.importCodeInfo.resourceId = '';
				this.importCodeInfo.boxHeaderName = '箱码';
				this.importCodeInfo.name = '';
				this.getDataListFn();
			}else{
				this.$message.error('导入失败，错误信息：'+res.erroMessage);
			}
		},
		// Excel文件上传成功
		excelUploadFn(val){
			this.importCodeInfo.resourceId = val.local;
		},
		// Excel文件删除
		excelRemoveFn(){
			this.importCodeInfo.resourceId = '';
		},
		async getShopListFn() {
			this.tableLoading = true;
			let params = {
				pageIndex: 1,
				pageSize: 999,
			}
			try {
				const res = await GetEnterprisesByPage(params);
				this.tableLoading = false;
				if (res.code === 200) {
					this.shopList = res.data.list;
					this.searchShop = res.data.list[2].id;
				} else {
					this.shopList = [];
					this.$message.error('获取店铺列表失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.tableLoading = false;
			}
		},
		// 打开箱码列表
		lookCodeBtnClick(id,name){
			this.boxCodeName = name;
			this.boxCodeId = id;
			this.lookBoxCodeDialog = true;
		},
		progressDialogClose(){
			clearInterval(this.timer);
			this.timer = null;
			this.progressText = '';
			this.progressDialog=false;
		},
		lookProgress(id,name){
			this.progressDialog=true
			this.percentage=0
			clearInterval(this.timer)
			let that = this;
			this.timer=setInterval(async ()=>{
				that.percentage= await that.getPercentageFn(id);
				if(this.percentage>=100){
					clearInterval(this.timer);
					this.getDataListFn();
					this.progressDialog=false;
				}
			},3000)
		},
		async getPercentageFn(id){
			let res = await GetTaskCompletionRatios({taskId:id});
			if(res.code===200){
				this.progressText = res.data.completed+'/'+res.data.total;
				return res.data.success?100:(res.data.completed/res.data.total).toFixed(2)*100
			}else{
				this.$message.error(res.erroMessage);
				clearInterval(this.timer)
				return false;
			}
		},
		cancelGenerate(id){
			this.$confirm('您将要取消生成任务, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await CancelTask({ taskId: id });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '取消成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('取消失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		// 删除商品
		deleteItemFn(id,isDelted) {
			let msg = isDelted?'彻底删除':'删除';
			this.$confirm('您将要'+msg+'该批次, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				this.loading = true;
				try {
					let res = await DeleteBoxCodeBatch({ id: id,Thoroughly:isDelted });
					this.loading = false;
					if (res.code === 200) {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getDataListFn();
					} else {
						this.$message.error('删除失败，错误信息：' + res.erroMessage);
					}
				} catch (error) {
					this.loading = false;
					this.erroMessageShow(error);
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		transactionCloas(){
			this.transactionTotal={}
		},
		addTransferOpen(){
			this.addBottleDialog=true
		},
		// 生成批次
		async createBottleCodeFn() {
			this.addBottleLoading = true;
			this.bottleConfig.enterpriseId = this.searchShop;
			let res = await StartGenerateCombinationCodesTask(this.bottleConfig);
			this.addBottleLoading = false;
			if (res.code === 200) {
				this.$message.success('生成批次成功');
				this.addBottleDialog = false;
				this.getDataListFn();
			} else {
				this.$message.error('生成批次失败，错误信息：' + res.erroMessage)
			}
		},
		// 关闭编辑积分信息窗口
		roleDialogClose() {
			this.bottleConfig = {
				boxSize:1,
				generateQuantity:1,
				name:''
			};
			this.addBottleLoading = false;
		},
		currentChange(val) {
			this.currentPage = val;
			this.getDataListFn();
		},
		async getDataListFn() {
			this.tableLoading = true;
			try {
				let params = {
					pageIndex: this.currentPage,
					pageSize: this.pageSize,
					EnterpriseId:this.searchShop
				}
				if(this.searchValue!==''){
					params.Name = this.searchValue;
				}
				if(this.searchBoxSize!==''){
					params.boxSize = this.searchBoxSize;
				}
				if(this.itemStatus!==''&&this.itemStatus!=='all'){
					params.Success = this.itemStatus;
				}
				if(this.BeginTime!==''&&this.BeginTime!==null&&this.BeginTime!==undefined){
					params.BeginTime = this.BeginTime;
				}
				if(this.EndTime!==''&&this.EndTime!==null&&this.EndTime!==undefined){
					params.EndTime = this.EndTime;
				}
				const res = await GetBoxCodeBatchesPage(params);
				this.tableLoading = false;
				if (res.code === 200) {
					this.tabelData = res.data.list;
					this.totalNum = res.data.totalCount;
				} else {
					this.tabelData = [];
					this.$message.error('获取积分列表失败，错误信息：' + res.erroMessage);
				}
			} catch (error) {
				this.tableLoading = false;
				this.$message.error('请求积分列表失败，错误信息：' + error);
			}
			
		},
	}
};
</script>
  
<style lang="scss" scoped>
.prcoss-container {
	box-sizing: border-box;
	padding: 20px;
	background-color: #fff;
}</style>